<template>
  <div class="main">
    <el-card>
      <div slot="header" class="clearfix">
        <span>音频列表</span>
      </div>
    </el-card>

    <el-card v-for="(item, index) in audioList" :key="item.id" class="card">
      <div class="content">
        <img
          :src="img"
          alt=""
          :class="{ 'rotate-image': isAudioPlaying(index) }"
          @click="toggleAudio(index)"
        />
        <p>{{ item.name }}</p>
        <audio
          :src="item.url"
          ref="audioPlayer"
          @play="handleAudioPlay(index)"
          @pause="handleAudioPause(index)"
          controls
        ></audio>
      </div>
    </el-card>

   
  </div>
</template>

<script setup>
import { getAudioApi } from "@/utils/api";
import { ref } from "vue";
import img from "@/assets/muc.jpg";


const audioList = ref([]);
const playingStates = ref([]);
const currentPlayingIndex = ref(null);

const init = async () => {
  const id = localStorage.getItem("id");
  getAudioApi({ id }).then((res) => {
    audioList.value = res.data.map((item) => {
      return {
        id: item.id,
        name: item.filename.split(".")[0],
        url: item.relativeFilePath,
      };
    });

    playingStates.value = Array(audioList.value.length).fill(false);
  });
};

const isAudioPlaying = (index) => {
  return playingStates.value[index];
};

const handleAudioPlay = (index) => {
  playingStates.value[index] = true;
  currentPlayingIndex.value = index;
};

const handleAudioPause = (index) => {
  playingStates.value[index] = false;
  currentPlayingIndex.value = null;
};

const toggleAudio = (index) => {
  const audioPlayer = $refs.audioPlayer[index];
  if (audioPlayer) {
    if (playingStates.value[index]) {
      audioPlayer.pause();
    } else {
      audioPlayer.play();
    }
  }
};





init();
</script>

<style lang="less" scoped>
img {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  border: 1px solid #ccc;
  transition: transform 0.5s ease-in-out;
}

.rotate-image {
  animation: rotateAnimation 2s linear infinite;
}

@keyframes rotateAnimation {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

.card {
  margin-top: 20px;
}

.content {
  width: 100%;
  height: 50px;
  display: flex;
  justify-content: space-around;
  align-items: center;
  margin: 20px;
}

.controls {
  margin-top: 20px;
  text-align: center;
}

.controls button {
  margin: 0 10px;
}
</style>
